import { FC, memo, useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { Breadcrumb as AntdBreadcrumb } from "antd";
import classNames from "classnames";

import { usePermissionStore } from "@/store";
import { IBaseComponentProps } from "@/types/component";

import "./index.scss";

interface Path {
  title: React.ReactNode;
}

export interface IBreadcrumbProps extends IBaseComponentProps {}

const prefixcls = "bread-crumb";

export const Breadcrumb: FC<IBreadcrumbProps> = memo((props) => {
  const { className } = props;

  const location = useLocation();
  const navigate = useNavigate();

  const { menuList } = usePermissionStore();

  const [routePath, setRoutePath] = useState<Path[]>();

  useEffect(() => {
    const paths = location.pathname.replace(/^\//, "").split("/");
    const findNodeByPath = (list: any, path: string) => {
      for (let node of list) {
        if (node.key === path) {
          return node;
        }
        if (node.children && node.children.length > 0) {
          let result: any = findNodeByPath(node.children, path);
          if (result) return result;
        }
      }
      // 如果没有找到匹配的节点，返回null
      return null;
    };
    const pathList = paths.map((path, index) => {
      const node = findNodeByPath(menuList, path);
      if (index === 0) {
        return {
          title: (
            <span
              onClick={() => {
                navigate(`/${node.key}/${node?.children[0].key}`);
              }}
              className="cursor-pointer crumb-item"
            >
              {node?.label}
            </span>
          ),
        };
      } else if (index === paths.length - 1) {
        return {
          title: <span>{node?.label}</span>,
        };
      } else {
        return {
          title: (
            <span
              className="cursor-pointer crumb-item"
              onClick={() => navigate("/" + paths.slice(0, index + 1).join("/"))}
            >
              {node?.label}
            </span>
          ),
        };
      }
    });
    setRoutePath(pathList);
  }, [location, menuList]);

  return (
    <div className={classNames(prefixcls, className)}>
      <AntdBreadcrumb items={routePath} />
    </div>
  );
});
